package com.dkm.ec.so.domain;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.dkm.base.api.model.Page;
import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.core.util.date.DateConverter;
import com.dkm.base.core.util.string.StringUtils;
import com.dkm.base.db.mybatis.impl.domain.MyBatisPage;
import com.dkm.biz.domain.AbstractDomain;
import com.dkm.biz.ou.persistence.entity.ShopStatPoEnum;
import com.dkm.biz.ou.service.ShopStatStatService;
import com.dkm.ec.constants.SaleStatConstants;
import com.dkm.ec.constants.SoReviewConstants;
import com.dkm.ec.product.domain.ProductEntity;
import com.dkm.ec.product.repository.ProductEntityRepository;
import com.dkm.ec.sale.domain.SaleSku;
import com.dkm.ec.sale.persistence.entity.SaleSkuPo;
import com.dkm.ec.sale.repository.SaleSkuRepository;
import com.dkm.ec.sale.service.SaleSkuStatService;
import com.dkm.ec.so.persistence.dao.SaleReviewDao;
import com.dkm.ec.so.persistence.entity.SaleReviewImgPo;
import com.dkm.ec.so.persistence.entity.SaleReviewPo;
import com.dkm.ec.so.persistence.entity.SaleReviewPoEnum;
import com.dkm.ec.so.persistence.entity.SoEntityPo;
import com.dkm.ec.so.persistence.entity.SoItemPo;
import com.dkm.ec.so.repository.SaleReviewImgRepository;
import com.dkm.ec.so.repository.SaleReviewRepository;
import com.dkm.ec.so.repository.SoEntityRepository;
import com.dkm.ec.so.repository.SoItemRepository;
import com.dkm.ou.me.domain.User;
import com.dkm.ou.me.persistence.entity.UserPo;
import com.dkm.ou.me.repository.UserRepository;

/**
 * 对象功能:产品评价 领域对象实体
 * 开发公司:SKG.COM
 * 开发人员:颜超敏
 * 创建时间:2015-02-10 11:03:42
 */
@SuppressWarnings("serial")
@Service
@Scope("prototype")
public class SaleReview extends AbstractDomain<String, SaleReviewPo>{
	@Resource
	private SaleReviewRepository saleReviewRepository;
	@Resource
	private SaleReviewImgRepository saleReviewImgRepository;
	@Resource
	private SaleSkuRepository saleSkuRepository;
	@Resource
	private SoItemRepository soItemRepository;
	@Resource
	private SaleReviewImg saleReviewImg;
	@Resource
	private UserRepository userRepository;
	@Resource
	private SaleSkuStatService saleSkuStatService;
	@Resource
	private SoEntityRepository soEntityRepository;
	@Resource
	private ShopStatStatService shopStatStatService;
	@Resource
	private ProductEntityRepository productEntityRepository;
	
	
	private SaleReviewDao saleReviewDao = null;

	
	private static Logger logger = LoggerFactory.getLogger(SaleReview.class);

	protected void init(){
		saleReviewDao = SpringHelper.getBean(SaleReviewDao.class);
		setDao(saleReviewDao);
	}	
	
	public List<SaleReviewPo> findSaleReviewForFrontPaged(SaleReviewPo lookUpObject, Page page){
		String type = lookUpObject.getType();
		if(StringUtils.isEmpty(type)){
			type = SaleReviewPo.TYPE.SHOW;
		}
		List<SaleReviewPo> saleReviewPos = saleReviewRepository.findSaleReviewForFrontPaged(lookUpObject.getCreateBy(),lookUpObject.getSoId(),lookUpObject.getProdId(),lookUpObject.getProdSkuId(), page,null,null, null);
		if(type.equals("show")){
			//load show
			for(SaleReviewPo saleReviewPo: saleReviewPos){
				List<SaleReviewImgPo> saleReviewImgPos = saleReviewImgRepository.findByReviewId(saleReviewPo.getId());
				saleReviewPo.setSaleReviewImgPos(saleReviewImgPos);
			}
		}
		return saleReviewPos;
	}

	public SaleReviewPo save(SaleReviewPo saleReviewPo,boolean isSkg) {
		Page page= new MyBatisPage();
		SaleReview saleReview=null;
		List<SaleReviewPo> saleReviewPos = saleReviewRepository.findSaleReviewForFrontPaged(saleReviewPo.getCreateBy(),saleReviewPo.getSoId(),saleReviewPo.getProdId(),saleReviewPo.getProdSkuId(),page,null,null, null);
		if(saleReviewPos!=null && saleReviewPos.size()>0){
			String id=saleReviewPos.get(0).getId();
			saleReview=saleReviewRepository.load(id);
			if(isSkg){
				SaleReviewPo po=saleReview.getData();
				po.setContent(saleReviewPo.getContent());
				po.setScore(saleReviewPo.getScore());
				po.setCreateTime(saleReviewPo.getCreateTime());
				saleReview.setData(po);
				saleReview.update();
				//是否添加图片
				saleReviewImg.addSaleReviewImg(saleReviewPo.getId(),saleReviewPo.getSaleReviewImgUrls());
			}
		}else{
			SoItemPo soItemPo = null;
		//	SoItemPo soItemPo=soItemRepository.getSoItemBySoIdAndProdSkuId(saleReviewPo.getSoId(),saleReviewPo.getProdSkuId());
			if(soItemPo!=null){
				//saleReviewPo.setAttrNames(soItemPo.getAttrNames());
				//saleReviewPo.setAttrOpLabels(soItemPo.getAttrOpLabels());
				SaleSku saleSku = saleSkuRepository.load(soItemPo.getProdSkuId());
				if(saleSku!=null){
					SaleSkuPo saleSkuPo=saleSku.getData();
					saleReviewPo.setProdId(saleSkuPo.getSaleProdId());
				}
				//saleReviewPo.setProdSkuName(soItemPo.getProdSkuName());
				saleReviewPo.setMainCloudPath(soItemPo.getMainCloudPath());
			
			}
			if(StringUtils.isEmpty(saleReviewPo.getContent())){
				saleReviewPo.setContent(SoReviewConstants.CONTENT);
			}
			saleReview=saleReviewRepository.newInstance();
			saleReviewPo.setId(getIdGenerator().genSid());
			User user=userRepository.load(saleReviewPo.getCreateBy());
			if(user!=null&&user.getData()!=null){
				UserPo userPo=user.getData();
			//	saleReviewPo.setPartyName(userPo.getPartyName());
				saleReviewPo.setProfile(userPo.getProfile());
			}
			
			saleReview.setData(saleReviewPo);
			saleReview.create();
			//SaleReviewAddEvent saleReviewEvent = new SaleReviewAddEvent(saleReview.getData());
			//SpringHelper.publishEvent(saleReviewEvent);
			
		}
		return saleReview.getData();
	
	}
	
	/**
	 * 获取审核信息
	 */
	public SaleReviewPo getThroughMsg(String saleReviewId) {
		List<String> ids = new ArrayList<>();
		ids.add(saleReviewId);
		List<SaleReviewPo> saleReviewPos = saleReviewRepository.findByIds(ids);
		SaleReviewPo saleReviewPo  = null;
		if(saleReviewPos != null && saleReviewPos.size() > 0){
			saleReviewPo = saleReviewPos.get(0);
			List<SaleReviewImgPo> saleReviewImgPos = saleReviewImgRepository.findByReviewId(saleReviewId);
			//同一商品前十个评论图片
			List<SaleReviewPo>  topTenSaleReviews = saleReviewRepository.findImageBySkuId(saleReviewPo.getProdSkuId(),saleReviewPo.getProdId());
			List<String> topSaleReviewIds = new ArrayList<>();
			for(SaleReviewPo topTenSaleReview : topTenSaleReviews){
				topSaleReviewIds.add(topTenSaleReview.getId());
			}
			if(topSaleReviewIds.contains(saleReviewPo.getId())){
				saleReviewPo.setTenTopFlag(true);
			} 
			if(saleReviewImgPos != null && saleReviewImgPos.size() > 0){
				saleReviewPo.setHasImageFlag(true);
				saleReviewPo.setSaleReviewImgPos(saleReviewImgPos);
			}
			if(saleReviewPo.getContent().length() >= 20){
				saleReviewPo.setSaleReviewlengFlag(true);
			}
			saleReviewPo.setContentLength(saleReviewPo.getContent().length());
		}
		return saleReviewPo;
	}
    /**
     * 审核评论及送积分 
     * @param isThrough 
     * @param id 
     */
	public void through(SaleReviewPo saleReviewPo, boolean isThrough, String id) {
	    String status ="pass";
	    String saleReviewId = "";
	    try{
	    	if(isThrough){//通过送积分
				saleReviewId = saleReviewPo.getId();
				if (StringUtils.isNotEmpty(saleReviewPo.getCreateBy())) {
					String createById = saleReviewPo.getCreateBy();
					
					Map<String, Object> jsonParam = new HashMap<String, Object>();
					jsonParam.put("wordNum", saleReviewPo.getContent().length());
					jsonParam.put("hasImg", saleReviewPo.isHasImageFlag()?"true":"false");
					jsonParam.put("hasTopTen", saleReviewPo.isTenTopFlag()?"true":"false");
			//		pointUpdateService.updatePoint(MemberConstants.GET_POINT_REVIEW, createById, saleReviewId, jsonParam);
				}
			}else {
				status = "no_pass";
				saleReviewId = id;
			}
			updateStatus(saleReviewId,status,saleReviewPo.getContent());
	    }catch(Exception e){
	    	logger.error(e.getMessage(), e);
	    }
	}
   private void updateStatus(String saleReviewId,String status,String content){
	   Map<String, Object> params=new HashMap<String, Object>();
		params.put("id", saleReviewId);
		params.put("status", status);
		if(StringUtils.isNotBlank(content)){
			params.put("content", content);
		}
		saleReviewDao.updateByKey("updatSaleReviewStatus", params);
   }

	public void throughs(String ids, String status) {
		Map<String, Object> params=new HashMap<String, Object>();
		if(StringUtils.isNotBlank(ids)){
			ids="('"+ids.replaceAll(",", "','")+"')";
			params.put("ids", ids);
			params.put("status", status);
			saleReviewDao.updateByKey("throughs", params);		
		}
		
	}

	public void taobaoDelete(String ids) {
		Map<String, Object> params=new HashMap<String, Object>();
		if(StringUtils.isNotBlank(ids)){
			ids="('"+ids.replaceAll(",", "','")+"')";
			params.put("ids", ids);
			saleReviewDao.updateByKey("taobaoDelete", params);		
		}
		
	}
	
	public void importSaleReviewDoUpdate(String id,String content){
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("id", id);
		params.put("content", content);
		saleReviewDao.updateByKey("importSaleReviewDoUpdate", params);
	}

	public void addReciews(List<SaleReviewPo> pos) throws ParseException {
		if(pos!=null){
			for(SaleReviewPo po:pos){
				if(StringUtils.isEmpty(po.getCreateTimeStr())||po.getCreateTimeStr().length()!=17){
					continue;
				}
				Date createTime=DateConverter.toDate(po.getCreateTimeStr(), "yyyy年MM月dd日 HH:mm");
				List<SaleReviewPo> temPos=saleReviewRepository.findByPartyNameAndCreateTime(po.getPartyName(),po.getCreateTimeStr());
				if(temPos!=null&&temPos.size()>0){
					continue;
				}
				SaleSkuPo saleSkuPo=saleSkuRepository.getSaleSkuPoByKey(po.getSaleKey());
				if(saleSkuPo!=null&&!StringUtils.isEmpty(saleSkuPo.getId())){
					po.setStatus("taobao");
					po.setScore(10);
					po.setProdId(saleSkuPo.getSaleProdId());
					po.setProdSkuId(saleSkuPo.getId());
					po.setAttrNames(saleSkuPo.getAttrNames());
					po.setAttrOpLabels(saleSkuPo.getAttrOpLabels());
					po.setProdSkuName(saleSkuPo.getSkuName());
					po.setCreateTime(createTime);
					po.setType(SaleReviewPo.TYPE.REVIEW);
					super.setData(po);
					super.create();
					saleSkuStatService.addProductStat(po.getProdId(), SaleStatConstants.TYPE_REVIEW, 1,new BigDecimal(0));
					saleSkuStatService.addSkuStat(po.getProdId(),po.getProdSkuId(), SaleStatConstants.TYPE_REVIEW, 1,new BigDecimal(0));
				}
				
			}
		}
		
	}

	public void createSaleReiewImg(String imgUrls,SaleReviewPo saleReviewPo) {
		 SoItem soItem = soItemRepository.load(saleReviewPo.getSoId());
		 SoItemPo soItemPo = soItem.getData();
		 saleReviewPo.setProdId(soItemPo.getProductId());
		 saleReviewPo.setProdSkuId(soItemPo.getProdSkuId());
         setData(saleReviewPo);
         save();
		 if(!StringUtils.isBlank(imgUrls)){
			   String[] imgs = imgUrls.split(",");
			   for(String img : imgs){
				   SaleReviewImgPo imgPo =new SaleReviewImgPo();
				   imgPo.setReviewId(saleReviewPo.getId());
				   imgPo.setImgUrl(img);
				   saleReviewImgRepository.newInstance(imgPo).save();
			   }
	     }
		 //订单评价
		 soItemPo.setIsReview('Y');
		 soItemRepository.newInstance(soItemPo).save();
		 List<SoItemPo> soItemPos = soItemRepository.findBySoEntityIdByIsReview(soItemPo.getSoId());
		 if(soItemPos.size() == 0){
			SoEntity soEntity =  soEntityRepository.load(soItemPo.getSoId());
			SoEntityPo soEntityPo = soEntity.getData();
			soEntityPo.setReviewStatus("all");
			soEntityRepository.newInstance(soEntityPo).save();
		 }
		 //商品评论统计
		String type = saleReviewPo.getType();
		String reviewType = "";
		if(SaleReviewPoEnum.good_review.toString().equals(type)){
			reviewType = SaleStatConstants.GOOD_REVIEW_QTY;
		}else if(SaleReviewPoEnum.middle_review.toString().equals(type)){
			reviewType = SaleStatConstants.MIDDLE_REVIEW_QTY;
		}else if(SaleReviewPoEnum.mistake_review.toString().equals(type)){
			reviewType = SaleStatConstants.MISTAKE_REVIEW_QTY;
		}
		//商品
		saleSkuStatService.addProductStat(soItemPo.getProductId(), reviewType, 1, new BigDecimal(0));
		saleSkuStatService.addProductStat(soItemPo.getProductId(), SaleStatConstants.TYPE_REVIEW, 1, new BigDecimal(0));
		
		ProductEntity productEntity =productEntityRepository.load(saleReviewPo.getProdId());
		if(productEntity != null){
			shopStatStatService.addShopStat(productEntity.getData().getShopId(), ShopStatPoEnum.score_qty_, 1);
		}
		
		//sku
		saleSkuStatService.addSkuStat(soItemPo.getProductId(), soItemPo.getProdSkuId(), reviewType, 1, new BigDecimal(0));
		saleSkuStatService.addSkuStat(soItemPo.getProductId(), soItemPo.getProdSkuId(), SaleStatConstants.TYPE_REVIEW, 1, new BigDecimal(0));
	}
	
}
